﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tomato.Libraries.Databases;
using Tomato.Libraries.Databases.Models;
using Tomato.Libraries.Patterns;

namespace Tomato.Libraries.Logging
{

    public class TomatoEventListener : EventListener
    {


        /// <summary>
        /// Called whenever an event has been written by an event source for which the event
        /// listener has enabled events.
        /// </summary>
        /// <param name="eventData"> The event arguments that describe the event. </param>
        protected override void OnEventWritten( EventWrittenEventArgs arguments )
        {

            var e = new Event
            {
                ActivityId    = arguments.ActivityId,
                EventId       = arguments.EventId,
                Level         = ( int ) arguments.Level,
                Opcode        = ( int ) arguments.Opcode,
                Payload       = arguments.Payload.First( ).ToString( ),
                EventKeywords = ( int ) arguments.Keywords,
                Task          = ( int ) arguments.Task,
                FormattedMessage = arguments.Message,
                ThreadId = Environment.CurrentManagedThreadId,
            };

            var db = new ExpenseDiaryDatabase( );
            db.Events.Save( e );

        }

        /// <summary>
        /// Called for all existing event sources when the event listener is created and when a new
        /// event source is attached to the listener.
        /// </summary>
        /// <param name="eventSource"> The event source. </param>
        /// <remarks>
        /// The listener processes any deferred enable events requests associated to the <paramref
        /// name="eventSource" />.
        /// </remarks>
        protected override void OnEventSourceCreated( EventSource eventSource )
        {

            try
            {

                base.OnEventSourceCreated( eventSource );

                if ( Singleton<TomatoEventListener>.Instance == null )
                {

                    // Do nothing.

                }
                else
                {

                    Singleton<TomatoEventListener>.Instance.EnableEvents( eventSource,
                        EventLevel.LogAlways, ( EventKeywords ) ( -1 ) );

                }

            }
            catch ( Exception e )
            {

                Debug.WriteLine( "{0}: Error in TomatoEventListener - {1}.",
                                 Environment.CurrentManagedThreadId,
                                 e.Message );
            }

        }

        /// <summary>
        /// Initializes this listener.
        /// </summary>
        public void Initialize( )
        {
            // What to initialize?
        }

    }

}